package com.weimengchao.controller;

import com.weimengchao.client.ProviderClient;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;


@RestController
public class TestController {

    @Resource
    RestTemplate restTemplate;
    @Resource
    LoadBalancerClient loadBalancerClient;
    @Resource
    ProviderClient providerClient;

    @GetMapping("hello2")
    public String hello2(@RequestParam String name) {
        String result = providerClient.hello(name);
        return result;
    }

    @GetMapping("hello")
    public String hello(@RequestParam String name) {
        String result = "";

        // 根据服务名获取服务实例
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-provider");

        // 发起调用
        URI uri = serviceInstance.getUri();
        result = restTemplate.getForObject(uri + "/hello?name=test", String.class);

        // 返回结果
        return result;
    }
}
